package com.fxl.majiang.service.impl;

import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxl.majiang.entity.MedicalAndPatientInfo;
import com.fxl.majiang.exception.CustomException;
import com.fxl.majiang.mapper.MedicalAndPatientInfoMapper;
import com.fxl.majiang.service.MedicalAndPatientInfoService;
import com.fxl.majiang.util.ExcelUtil;
import com.fxl.majiang.util.MapUtil;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;

@Service
public class MedicalAndPatientInfoServiceImpl extends ServiceImpl<MedicalAndPatientInfoMapper, MedicalAndPatientInfo> implements MedicalAndPatientInfoService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void upload(MultipartFile file) throws Exception {
        if (file == null || !StringUtils.hasText(file.getOriginalFilename())) {
            throw new CustomException("文件或者文件名不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        System.out.println("文件名称:" + originalFilename);
        String[] fileNameArr = originalFilename.split("\\.");
        String suffix = fileNameArr[fileNameArr.length - 1];
        Workbook wb = null;
        InputStream fis = file.getInputStream();   //文件流对象
        //根据文件后缀（xls/xlsx）进行判断
        if ("xls".equals(suffix)){
            wb = new HSSFWorkbook(fis);
        }else if ("xlsx".equals(suffix)){
            wb = new XSSFWorkbook(fis);
        } else {
            throw new CustomException("文件格式以及后缀必须为xls/xlsx");
        }

        List<MedicalAndPatientInfo> entities = new ArrayList<>();
        if (wb.getNumberOfSheets() > 100) {
            throw new CustomException("最多只能上传100个sheet");
        }
        Iterator<Sheet> sheetIterator = wb.sheetIterator();
        while (sheetIterator.hasNext()) {
            Sheet sheet = sheetIterator.next();
            try {
                MedicalAndPatientInfo entity = new MedicalAndPatientInfo();
                Row row1 = sheet.getRow(1);
                entity.setPatientName(ExcelUtil.getCellValue(row1.getCell(1)));
                entity.setApplicantName(ExcelUtil.getCellValue(row1.getCell(3)));
                Row row2 = sheet.getRow(2);
                entity.setPatientAge(ExcelUtil.getCellValue(row2.getCell(1)));
                entity.setApplicantPhone(ExcelUtil.getCellValue(row2.getCell(3)));
                Row row3 = sheet.getRow(3);
                entity.setPatientGender(ExcelUtil.getCellValue(row3.getCell(1)));
                Row row4 = sheet.getRow(4);
                entity.setPatientIdCardType(ExcelUtil.getCellValue(row4.getCell(1)));
                Row row5 = sheet.getRow(5);
                entity.setPatientIdCardNum(ExcelUtil.getCellValue(row5.getCell(1)));
                Row row6 = sheet.getRow(6);
                entity.setPatientMedicalInsurance(ExcelUtil.getCellValue(row6.getCell(1)));
                Row row7 = sheet.getRow(7);
                entity.setPatientPhone(ExcelUtil.getCellValue(row7.getCell(1)));
                Row row8 = sheet.getRow(8);
                entity.setPatientMedicalCardNumber(ExcelUtil.getCellValue(row8.getCell(1)));
                Row row10 = sheet.getRow(10);
                entity.setAppointmentDoctorName(ExcelUtil.getCellValue(row10.getCell(1)));
                Row row11 = sheet.getRow(11);
                entity.setAppointmentDoctorDuties(ExcelUtil.getCellValue(row11.getCell(1)));
                Row row12 = sheet.getRow(12);
                entity.setAppointmentDoctorFirstLevelDepartment(ExcelUtil.getCellValue(row12.getCell(1)));
                Row row13 = sheet.getRow(13);
                entity.setAddress(ExcelUtil.getCellValue(row13.getCell(1)));
                entity.setCreateTime(new Date());
                entity.setUpdateTime(new Date());
                entity.setFileName(originalFilename);
                entity.setSheetName(sheet.getSheetName());
                entity.setIsDeleted(0);
                entities.add(entity);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("sheet[" +sheet.getSheetName() + "]数据有问题，请检查");
            }
        }

        this.saveBatch(entities);
    }

    @Override
    public void export(HttpServletResponse response) throws Exception {
        List<HashMap<String, String>> titleList = new ArrayList<>();
        titleList.add(ExcelUtil.makeTitleMap("id", "id"));
        titleList.add(ExcelUtil.makeTitleMap("申请人姓名", "applicant_name"));
        titleList.add(ExcelUtil.makeTitleMap("电话", "applicant_phone"));
        titleList.add(ExcelUtil.makeTitleMap("医生姓名", "appointment_doctor_name"));
        titleList.add(ExcelUtil.makeTitleMap("职务", "appointment_doctor_duties"));
        titleList.add(ExcelUtil.makeTitleMap("一级科室", "appointment_doctor_first_level_department"));
        titleList.add(ExcelUtil.makeTitleMap("地址", "address"));
        titleList.add(ExcelUtil.makeTitleMap("患者姓名", "patient_name"));
        titleList.add(ExcelUtil.makeTitleMap("年龄", "patient_age"));
        titleList.add(ExcelUtil.makeTitleMap("性别", "patient_gender"));
        titleList.add(ExcelUtil.makeTitleMap("证件类型", "patient_id_card_type"));
        titleList.add(ExcelUtil.makeTitleMap("证件号码", "patient_id_card_num"));
        titleList.add(ExcelUtil.makeTitleMap("医保", "patient_medical_insurance"));
        titleList.add(ExcelUtil.makeTitleMap("电话", "patient_phone"));
        titleList.add(ExcelUtil.makeTitleMap("录入时间", "create_time_format"));
        titleList.add(ExcelUtil.makeTitleMap("录入文件名称", "file_name"));
        titleList.add(ExcelUtil.makeTitleMap("录入sheet名称", "sheet_name"));

        List<HashMap<String, Object>> dataList = baseMapper.selectAllList();
        if (!CollectionUtils.isEmpty(dataList)) {
            ExcelUtil.exportExcelSxssf("MedicalAndPatientInfo_" +System.currentTimeMillis() , titleList, dataList, response);
        } else {
            throw new CustomException("无数据");
        }
    }
}
